<template>
  <el-dialog
    v-model="state.visible"
    :title="state.title"
    width="1400px"
    draggable
    :close-on-click-modal="false"
    @close="handleClose"
    class="batch-approval-dialog"
  >
    <div class="batch-approval-content">
      <!-- 批量操作设置 -->
      <div class="batch-settings-section">
        <div class="compact-settings">
          <!-- 操作类型 -->
          <div class="setting-item">
            <label class="item-label">操作类型</label>
            <el-radio-group v-model="state.form.action" @change="handleActionChange" size="small">
              <el-radio value="approve">
                <el-icon><Check /></el-icon>
                批量同意
              </el-radio>
              <el-radio value="reject">
                <el-icon><Close /></el-icon>
                批量拒绝
              </el-radio>
            </el-radio-group>
          </div>

          <!-- 确认人设置（仅同意操作显示） -->
          <div class="setting-item" v-if="state.form.action === 'approve'">
            <label class="item-label">确认人设置</label>
            <div class="confirmer-control">
              <el-select
                v-model="state.form.globalConfirmerId"
                placeholder="选择确认人"
                filterable
                clearable
                size="small"
                style="width: 160px"
                :disabled="state.form.confirmerLocked"
                @change="handleGlobalConfirmerChange"
              >
                <el-option
                  v-for="user in userOptions"
                  :key="user.id"
                  :label="user.realName"
                  :value="user.id"
                >
                  <div class="user-option">
                    <span class="user-name">{{ user.realName }}</span>
                    <span class="user-org">{{ user.orgName }}</span>
                  </div>
                </el-option>
              </el-select>
              <el-button 
                :icon="state.form.confirmerLocked ? Lock : Unlock" 
                @click="toggleGlobalConfirmerLock"
                :type="state.form.confirmerLocked ? 'danger' : 'success'"
                size="small"
              >
                {{ state.form.confirmerLocked ? '解锁' : '锁定' }}
              </el-button>
            </div>
          </div>

          <!-- 统一备注 -->
          <div class="setting-item">
            <label class="item-label">统一备注</label>
            <el-input
              v-model="state.form.globalRemark"
              placeholder="输入统一的审批意见（可选）"
              :maxlength="100"
              size="small"
              style="width: 200px"
            />
          </div>

          <!-- 操作按钮 -->
          <div class="setting-item">
            <div class="item-actions">
              <el-button 
                type="primary" 
                :icon="Check" 
                @click="applyGlobalSettings" 
                :disabled="selectedItems.length === 0"
                size="small"
              >
                应用设置
              </el-button>
              <el-button 
                type="info" 
                :icon="Refresh" 
                @click="resetGlobalSettings"
                size="small"
              >
                重置
              </el-button>
            </div>
          </div>

          <!-- 状态显示 -->
          <div class="setting-item">
            <el-tag type="info">共 {{ selectedItems.length }} 项</el-tag>
            <!-- 锁定提示（内联显示） -->
            <div class="inline-note" v-if="state.form.action === 'approve' && state.form.confirmerLocked">
              <el-divider direction="vertical" />
              <el-icon><InfoFilled /></el-icon>
              <span>确认人已锁定，将使用直属主管</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 批量审批列表 -->
      <div class="batch-list-section">
        <div class="list-header">
          <span class="list-title">
            <el-icon><List /></el-icon>
            批量审批列表
          </span>
          <div class="header-actions">
            <el-button
              size="small"
              type="success"
              :icon="state.form.action === 'approve' ? Check : Close"
              @click="selectAll"
              :disabled="selectedItems.length === 0"
            >
              全选{{ state.form.action === 'approve' ? '同意' : '拒绝' }}
            </el-button>
          </div>
        </div>
        <el-table
          :data="selectedItems"
          style="width: 100%"
          tooltip-effect="light"
          row-key="id"
          border
          max-height="400"
        >
          <el-table-column type="index" label="序号" width="55" align="center" fixed="left" />
          <el-table-column prop="flowType" label="类型" width="80" align="center" fixed="left">
            <template #default="scope">
              <el-tag :type="scope.row.flowType === '入库' ? 'success' : 'warning'">{{ scope.row.flowType }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="requestNo" label="申请号" width="160" fixed="left" show-overflow-tooltip />
          <el-table-column prop="materialName" label="物资名称" width="180" show-overflow-tooltip />
          <el-table-column label="申请信息" width="120" align="center">
            <template #default="scope">
              <div>{{ scope.row.quantity }} {{ scope.row.unit }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="applicantName" label="申请人" width="100" show-overflow-tooltip />
          <el-table-column label="批准数量" width="140" align="center" v-if="state.form.action === 'approve'">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.approvedQuantity"
                :min="1"
                :max="scope.row.quantity"
                :precision="0"
                size="small"
                style="width: 120px"
              />
            </template>
          </el-table-column>
          <el-table-column label="确认人" width="180" v-if="state.form.action === 'approve'">
            <template #default="scope">
              <el-select
                v-model="scope.row.confirmerId"
                placeholder="选择确认人"
                filterable
                clearable
                size="small"
                style="width: 160px"
                @change="handleItemConfirmerChange(scope.row, $event)"
              >
                <el-option
                  v-for="user in userOptions"
                  :key="user.id"
                  :label="user.realName"
                  :value="user.id"
                >
                  <div class="user-option">
                    <span class="user-name">{{ user.realName }}</span>
                    <span class="user-org">{{ user.orgName }}</span>
                  </div>
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="审批意见" width="200">
            <template #default="scope">
              <el-input
                v-model="scope.row.remark"
                placeholder="审批意见（可选）"
                size="small"
                maxlength="100"
                show-word-limit
                clearable
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center" fixed="right">
            <template #default="scope">
              <el-switch
                v-model="scope.row.selected"
                active-text="同意"
                inactive-text="跳过"
                active-color="#67c23a"
                inline-prompt
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <template #footer>
      <div class="batch-approval-footer">
        <div class="footer-info">
          <el-text type="info">
            已选择 {{ selectedItems.filter(item => item.selected).length }} / {{ selectedItems.length }} 项进行同意操作
          </el-text>
        </div>
        <div class="footer-actions">
          <el-button @click="handleClose">取消</el-button>
          <el-button
            type="primary"
            color="#67c23a"
            @click="handleSubmit"
            :loading="state.loading"
            :disabled="selectedItems.filter(item => item.selected).length === 0"
          >
            <el-icon>
              <Check />
            </el-icon>
            批量同意
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
// cspell:ignore confirmer Confirmer
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Check, Close, Lock, Unlock, Setting, List, InfoFilled, Refresh } from '@element-plus/icons-vue';
import { getAPI } from '/@/utils/axios-utils';
import { SysUserApi } from '/@/api-services/api';
import { useUserInfo } from '/@/stores/userInfo';

interface User {
  id: number;
  realName: string;
  orgName?: string;
  posName?: string;
}

interface BatchApprovalItem {
  id: number;
  flowType: string;
  requestNo: string;
  materialName: string;
  quantity: number;
  unit: string;
  applicantName: string;
  approvedQuantity?: number;
  confirmerId?: number;
  confirmerName?: string;
  remark?: string;
  selected: boolean;
  [key: string]: any;
}

interface BatchForm {
  action: 'approve' | 'reject';
  globalConfirmerId: number | null;
  globalConfirmerName: string;
  globalRemark: string;
  confirmerLocked: boolean;
}

const emit = defineEmits<{
  'submit': [data: {
    action: 'approve' | 'reject';
    items: BatchApprovalItem[];
  }];
}>();

const userOptions = ref<User[]>([]);
const userInfo = useUserInfo();

const toNumberOrUndefined = (value: unknown): number | undefined => {
  const num = Number(value);
  return Number.isFinite(num) ? num : undefined;
};

const isExecutionStage = (item: BatchApprovalItem | null) => {
  if (!item) return false;
  const currentStep = Number(item.currentStep ?? 1);
  if (item.flowType === '入库') {
    return currentStep >= 2;
  }
  if (item.flowType === '出库') {
    return currentStep >= 3;
  }
  return false;
};

const state = reactive({
  visible: false,
  loading: false,
  title: '',
  form: {
    action: 'approve',
    globalConfirmerId: null,
    globalConfirmerName: '',
    globalRemark: '',
    confirmerLocked: true,
  } as BatchForm,
});

const selectedItems = ref<BatchApprovalItem[]>([]);

// 页面加载时获取用户列表
onMounted(async () => {
  await loadUserOptions();
});

// 加载用户选项
const loadUserOptions = async () => {
  try {
    const params = {
      page: 1,
      pageSize: 100,
      status: 1, // 只获取启用的用户
    };
    const result = await getAPI(SysUserApi).apiSysUserPagePost(params);
    userOptions.value = (result.data.result?.items || []).map((user: any) => ({
      id: user.id || 0,
      realName: user.realName || '',
      orgName: user.orgName || '',
      posName: user.posName || '',
    }));
  } catch (error) {
    console.error('加载用户列表失败:', error);
    ElMessage.error('加载用户列表失败');
  }
};

// 处理操作类型变化
const handleActionChange = (action: 'approve' | 'reject') => {
  // 设置默认备注
  state.form.globalRemark = action === 'approve' ? '同意' : '拒绝';
  
  // 重置所有项目的选择状态
  selectedItems.value.forEach(item => {
    item.selected = true; // 默认选中所有
    if (action === 'approve') {
      // 同意操作，设置默认批准数量
      if (!item.approvedQuantity) {
        item.approvedQuantity = item.quantity;
      }
    } else {
      // 拒绝操作，清除批准数量和确认人
      delete item.approvedQuantity;
      delete item.confirmerId;
      delete item.confirmerName;
    }
  });
};

// 处理全局确认人变化
const handleGlobalConfirmerChange = (userId: number | null) => {
  if (userId) {
    const selectedUser = userOptions.value.find(user => user.id === userId);
    if (selectedUser) {
      state.form.globalConfirmerId = userId;
      state.form.globalConfirmerName = selectedUser.realName;
    }
  } else {
    state.form.globalConfirmerId = null;
    state.form.globalConfirmerName = '';
  }
};

// 切换全局确认人锁定状态
const toggleGlobalConfirmerLock = () => {
  state.form.confirmerLocked = !state.form.confirmerLocked;
  if (state.form.confirmerLocked) {
    // 锁定时清空选择
    state.form.globalConfirmerId = null;
    state.form.globalConfirmerName = '';
  }
};

// 处理单个项目确认人变化
const handleItemConfirmerChange = (item: BatchApprovalItem, userId: number | null) => {
  if (userId) {
    const selectedUser = userOptions.value.find(user => user.id === userId);
    if (selectedUser) {
      item.confirmerId = userId;
      item.confirmerName = selectedUser.realName;
    }
  } else {
    delete item.confirmerId;
    delete item.confirmerName;
  }
};

// 应用全局设置
const applyGlobalSettings = () => {
  ElMessageBox.confirm(
    `确定要将全局设置应用到所有 ${selectedItems.value.length} 个项目吗？`,
    '应用全局设置',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    selectedItems.value.forEach(item => {
      const executionStage = isExecutionStage(item);
      const currentUserId = toNumberOrUndefined(userInfo.userInfos?.id);
      if (state.form.action === 'approve') {
        // 设置确认人
        if (executionStage && currentUserId !== undefined) {
          item.confirmerId = currentUserId;
          item.confirmerName = userInfo.userInfos?.realName ?? '';
        } else if (state.form.confirmerLocked) {
          // 锁定时使用直属主管
          const managerId = toNumberOrUndefined(userInfo.userInfos?.managerUserId);
          if (managerId !== undefined) {
            const managerUser = userOptions.value.find(user => user.id === managerId);
            if (managerUser) {
              item.confirmerId = managerUser.id;
              item.confirmerName = managerUser.realName;
            }
          }
        } else if (state.form.globalConfirmerId) {
          // 解锁时使用选择的确认人
          item.confirmerId = state.form.globalConfirmerId ?? undefined;
          item.confirmerName = state.form.globalConfirmerName;
        }
        
        // 设置默认批准数量（如果尚未设置）
        if (!item.approvedQuantity) {
          item.approvedQuantity = item.quantity;
        }
      }
      
      // 设置备注
      if (state.form.globalRemark) {
        item.remark = state.form.globalRemark;
      }
      
      // 默认选中
      item.selected = true;
    });
    
    ElMessage.success('全局设置已应用到所有项目');
  });
};

// 重置全局设置
const resetGlobalSettings = () => {
  state.form.globalConfirmerId = null;
  state.form.globalConfirmerName = '';
  state.form.globalRemark = '';
  
  selectedItems.value.forEach(item => {
    delete item.confirmerId;
    delete item.confirmerName;
    item.remark = '';
    item.selected = false;
    if (state.form.action === 'approve') {
      item.approvedQuantity = item.quantity;
    }
  });
  
  ElMessage.success('全局设置已重置');
};

// 全选操作
const selectAll = () => {
  const allSelected = selectedItems.value.every(item => item.selected);
  selectedItems.value.forEach(item => {
    item.selected = !allSelected;
  });
};

// 打开批量同意弹窗
const openDialog = (items: any[], action: 'approve' | 'reject' = 'approve') => {
  if (!items || items.length === 0) {
    ElMessage.warning('请先选择要审批的项目');
    return;
  }
  
  // 过滤可以审批的项目（与单独审批逻辑保持一致）
  const approvalItems = items.filter(item => {
    // 待审核状态 - 所有流程
    if (item.approvalAction === 1) return true;
    
    // 入库第2步已审批状态 - 等待仓储人员完成
    if (item.approvalAction === 3 && item.flowType === '入库' && item.currentStep === 2) return true;
    
    // 出库已审核状态 - 等待进一步审批
    if (item.approvalAction === 2 && item.flowType === '出库') return true;
    
    // 出库已审批状态 - 等待仓储人员完成
    if (item.approvalAction === 3 && item.flowType === '出库' && item.currentStep === 3) return true;
    
    return false;
  });
  
  if (approvalItems.length === 0) {
    ElMessage.warning('所选项目中没有可审批的项目');
    return;
  }
  
  if (approvalItems.length < items.length) {
    ElMessage.info(`已过滤掉 ${items.length - approvalItems.length} 个不可审批项目`);
  }
  
  state.form.action = 'approve'; // 强制设置为同意模式
  state.title = `批量同意审批 - ${approvalItems.length} 项`;
  
  // 初始化项目数据
  selectedItems.value = approvalItems.map(item => {
    const executionStage = isExecutionStage(item);
    const currentUserId = toNumberOrUndefined(userInfo.userInfos?.id);
    const defaultConfirmerId = executionStage ? currentUserId : undefined;
    const defaultConfirmerName = executionStage && currentUserId !== undefined ? (userInfo.userInfos?.realName ?? '') : '';

    return {
      ...item,
      approvedQuantity: action === 'approve' ? item.quantity : undefined,
      confirmerId: defaultConfirmerId,
      confirmerName: defaultConfirmerId !== undefined ? defaultConfirmerName : '',
      remark: '',
      selected: true,
    };
  });
  
  // 重置全局设置状态
  state.form.globalConfirmerId = null;
  state.form.globalConfirmerName = '';
  state.form.globalRemark = '同意'; // 设置默认备注
  state.form.confirmerLocked = true;

  state.visible = true;
};

// 关闭弹窗
const handleClose = () => {
  state.visible = false;
  state.loading = false;
  selectedItems.value = [];
  state.form = {
    action: 'approve',
    globalConfirmerId: null,
    globalConfirmerName: '',
    globalRemark: '',
    confirmerLocked: true,
  };
};

// 提交批量审批
const handleSubmit = async () => {
  // 防重复提交：若已在提交或确认中，则直接返回
  if (state.loading) return;

  // 进入提交流程，先锁定按钮，防止连点导致多次弹出确认框
  state.loading = true;
  const selectedItemsForSubmit = selectedItems.value.filter(item => item.selected);
  
  if (selectedItemsForSubmit.length === 0) {
    ElMessage.warning('请至少选择一个项目进行操作');
    state.loading = false;
    return;
  }
  
  // 验证同意操作的必填项
  if (state.form.action === 'approve') {
    const invalidItems = selectedItemsForSubmit.filter(item => 
      !item.approvedQuantity || item.approvedQuantity <= 0 || item.approvedQuantity > item.quantity
    );
    
    if (invalidItems.length > 0) {
      ElMessage.warning(`有 ${invalidItems.length} 个项目的批准数量不正确`);
      state.loading = false;
      return;
    }
    
    // 检查审批阶段是否必须指定确认人
    const itemsNeedingConfirmer = selectedItemsForSubmit.filter(item => {
      // 对于审批阶段（currentStep >= 2），必须指定确认人
      if (isExecutionStage(item)) {
        return false;
      }
      return item.currentStep >= 2 && (!item.confirmerId || item.confirmerId <= 0);
    });
    
    if (itemsNeedingConfirmer.length > 0) {
      ElMessage.error(`有 ${itemsNeedingConfirmer.length} 个审批项目未指定确认人，请为所有审批项目选择确认人`);
      state.loading = false;
      return;
    }
    
    // 为没有设置确认人的非审批阶段项目自动分配直属主管
    for (const item of selectedItemsForSubmit) {
      if (item.confirmerId && item.confirmerId > 0) continue;

      if (isExecutionStage(item)) {
        const currentUserId = toNumberOrUndefined(userInfo.userInfos?.id);
        if (currentUserId !== undefined) {
          item.confirmerId = currentUserId;
          item.confirmerName = userInfo.userInfos?.realName ?? '';
        }
        continue;
      }

      if (item.currentStep < 2) {
        const managerId = toNumberOrUndefined(userInfo.userInfos?.managerUserId);
        if (managerId === undefined) continue;
        const managerUser = userOptions.value.find(user => user.id === managerId);
        if (managerUser) {
          item.confirmerId = managerUser.id;
          item.confirmerName = managerUser.realName;
        }
      }
    }
  }
  
  const actionText = state.form.action === 'approve' ? '同意' : '拒绝';
  
  try {
    await ElMessageBox.confirm(
      `确定要${actionText} ${selectedItemsForSubmit.length} 个审批项目吗？`,
      `批量${actionText}确认`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    emit('submit', {
      action: state.form.action,
      items: selectedItemsForSubmit,
    });
    
    handleClose();
    
  } catch (error) {
    // 用户取消
  } finally {
    state.loading = false;
  }
};

// 暴露方法
defineExpose({
  openDialog,
});
</script>

<style lang="scss" scoped>
/* 弹窗整体样式 */
:deep(.batch-approval-dialog) {
  .el-dialog__header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 8px 8px 0 0;
    padding: 20px 24px;
  }
  
  .el-dialog__title {
    color: white;
    font-weight: 600;
    font-size: 16px;
  }
  
  .el-dialog__body {
    padding: 24px;
  }
}

.batch-approval-content {
  .mb-4 {
    margin-bottom: 20px;
  }
}

/* 批量设置区域 */
.batch-settings-section {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px 20px;
  margin-bottom: 20px;
  border: 1px solid #e9ecef;
}

.compact-settings {
  display: flex;
  align-items: center;
  gap: 24px;
  flex-wrap: wrap;
}

.setting-item {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .item-label {
    font-size: 13px;
    font-weight: 600;
    color: #495057;
    white-space: nowrap;
  }
  
  .confirmer-control {
    display: flex;
    align-items: center;
    gap: 6px;
  }
  
  .item-actions {
    display: flex;
    gap: 6px;
  }
}

/* 批量列表区域 */
.batch-list-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #dee2e6;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e9ecef;
}

.list-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  font-size: 16px;
  color: #495057;
  
  .el-icon {
    color: #6c757d;
  }
}

.header-actions {
  display: flex;
  gap: 8px;
}

.inline-note {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #1976d2;
  margin-left: 8px;
  
  .el-icon {
    color: #1976d2;
  }
  
  :deep(.el-divider--vertical) {
    height: 12px;
    margin: 0 4px;
    border-left: 1px solid #e0e0e0;
  }
}

/* 表单样式统一 */
:deep(.el-form-item__label) {
  color: #495057;
  font-weight: 500;
}

.confirmer-input-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-option {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .user-name {
    font-weight: 500;
    color: #212529;
  }
  
  .user-org {
    color: #6c757d;
    font-size: 12px;
  }
}

.batch-approval-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0 0 0;
  border-top: 1px solid #dee2e6;
  
  .footer-info {
    font-size: 14px;
    color: #6c757d;
    background: #f8f9fa;
    padding: 8px 12px;
    border-radius: 6px;
    border-left: 3px solid #0d6efd;
  }
  
  .footer-actions {
    display: flex;
    gap: 12px;
  }
}

/* 表格样式优化 */
:deep(.el-table) {
  font-size: 13px;
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f8f9fa;
  color: #495057;
  font-weight: 600;
  border-bottom: 2px solid #e9ecef;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f8f9fa;
  vertical-align: middle;
}

:deep(.el-table__row:hover > td) {
  background-color: #f8f9fa;
}

/* 表单控件样式 */
:deep(.el-radio-group) {
  display: flex;
  gap: 20px;
}

:deep(.el-radio__label) {
  color: #495057;
  font-weight: 500;
}

:deep(.el-input-number) {
  width: 120px;
}

:deep(.el-switch__label) {
  font-size: 12px;
  color: #6c757d;
}

:deep(.el-button--small) {
  border-radius: 6px;
  font-weight: 500;
}
</style>
